package com.example.core.license.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

public class LicenseCustomManager extends LicenseManager {

    private static final String XML_CHARSET = "UTF-8";
    /**
     * 默认BUFF_SIZE
     */
    private static final int DEFAULT_BUFF_SIZE = 8 * 1024;

    Logger logger = LoggerFactory.getLogger(getClass());

    public LicenseCustomManager(LicenseParam param) {
        super(param);
    }

    /**
     * <p>重写LicenseManager的create方法</p>
     *
     * @param content LicenseContent 证书信息
     * @param notary  notary 公正信息
     * @return byte[]
     * @throws Exception 默认异常
     */
    @Override
    protected synchronized byte[] create(LicenseContent content, LicenseNotary notary) throws Exception {
        initialize(content);
        this.validateCreate(content);
        final GenericCertificate certificate = notary.sign(content);
        return getPrivacyGuard().cert2key(certificate);
    }


    /**
     * <p>重写install方法</p>
     *
     * @param key    密匙
     * @param notary 公正信息
     * @return LicenseContent 证书信息
     * @throws Exception 默认异常
     */
    @Override
    protected synchronized LicenseContent install(final byte[] key, final LicenseNotary notary) throws Exception {
        final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent licenseContent = (LicenseContent) this.load(certificate.getEncoded());
        this.validate(licenseContent);
        setLicenseKey(key);
        setCertificate(certificate);
        return licenseContent;
    }

    /**
     * <p>重写verify方法</p>
     *
     * @param notary 公正信息
     * @return LicenseContent 证书信息
     * @throws Exception 默认异常
     */
    @Override
    protected synchronized LicenseContent verify(final LicenseNotary notary) throws Exception {
        final byte[] key = getLicenseKey();
        if (null == key) {
            throw new NoLicenseInstalledException(getLicenseParam().getSubject());
        }
        GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
        this.validate(content);
        setCertificate(certificate);
        return content;
    }

    /**
     * <p>校验生成证书的参数信息</p>
     *
     * @param content LicenseContent 证书内容
     * @throws LicenseContentException 证书内容错误异常
     */
    protected synchronized void validateCreate(final LicenseContent content) throws LicenseContentException {
        final Date now = new Date();
        final Date notBefore = content.getNotBefore();
        final Date notAfter = content.getNotAfter();
        if (null != notAfter && now.after(notAfter)) {
            String message = "证书失效时间不能早于当前时间";
            logger.error(message);
            throw new LicenseContentException(message);
        }
        if (null != notBefore && null != notAfter && notAfter.before(notBefore)) {
            String message = "证书生效时间不能晚于证书失效时间";
            logger.error(message);
            throw new LicenseContentException(message);
        }
        final String consumerType = content.getConsumerType();
        if (null == consumerType) {
            String message = "用户类型不能为空";
            logger.error(message);
            throw new LicenseContentException(message);
        }
    }

    /**
     * <p>重写validate方法，增加ip地址、mac地址、cpu序列号等其他信息的校验</p>
     *
     * @param content LicenseContent 证书内容
     * @throws LicenseContentException 证书内容错误异常
     */
    @Override
    protected synchronized void validate(final LicenseContent content) throws LicenseContentException {
        final Date now = new Date();
        if (now.after(content.getNotAfter())) {
            throw new LicenseContentException("系统证书过期，当前时间已超过证书结束时间 -- " +
                    DateUtil.format(content.getNotAfter(), DatePattern.NORM_DATE_PATTERN));
        }
        if (now.before(content.getNotBefore())) {
            throw new LicenseContentException("系统证书过期，当前时间不能早于证书开始时间 -- " +
                    DateUtil.format(content.getNotBefore(), DatePattern.NORM_DATE_PATTERN));
        }
        super.validate(content);
        Map<String, String> map = (Map<String, String>) content.getExtra();
        if (map.containsKey("ip") && map.get("ip") != null) {
            if (!NetUtil.localIps().contains(map.get("ip"))) {
                throw new LicenseContentException("系统证书绑定IP不对，许可绑定ip如下: -- " +
                        map.get("ip"));
            }
        }
        String macAddress = NetUtil.getLocalMacAddress();
        if (map.containsKey("mac") && map.get("mac") != null) {
            if (!map.get("mac").contains(NetUtil.getLocalMacAddress())) {
                throw new LicenseContentException("系统证书绑定MAC不对，许可绑定MAC如下: -- " +
                        map.get("mac"));
            }
        }
    }

    /**
     * <p>重写XMLDecoder解析XML</p>
     */
    private Object load(String encoded) {
        BufferedInputStream inputStream = null;
        XMLDecoder decoder = null;
        try {
            inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET)));
            decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFF_SIZE), null, null);
            return decoder.readObject();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            try {
                if (decoder != null) {
                    decoder.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("XMLDecoder解析XML失败", e);
            }
        }
        return null;
    }
}
